package com.enzoism.java;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * Created by enzoism on 2019/6/9.
 */
public class ApplicationStartupUtil
{
    // 所有要预检查的服务列表
    private static List<BaseHealthChecker> _services;

    // 定时器
    private static CountDownLatch _latch;

    private ApplicationStartupUtil() {
    }

    private final static ApplicationStartupUtil INSTANCE = new ApplicationStartupUtil();

    public static ApplicationStartupUtil getInstance() {
        return INSTANCE;
    }

    public static boolean checkExternalServices() throws Exception
    {
        // 初始化定时器的定时任务数量
        _latch = new CountDownLatch(3);

        // 添加要检查的服务列表
        _services = new ArrayList<BaseHealthChecker>();
        _services.add(new NetworkHealthChecker(_latch));
        _services.add(new CacheHealthChecker(_latch));
        _services.add(new DatabaseHealthChecker(_latch));

        // 线程调度器创建
        Executor executor = Executors.newFixedThreadPool(_services.size());
        for(final BaseHealthChecker v : _services) {
            executor.execute(v);
        }

        // 进行定时器等待
        _latch.await();

        // 判断所有服务是否都已经启动
        for(final BaseHealthChecker v : _services)
        {
            if( ! v.isServiceUp())
            {
                return false;
            }
        }
        return true;
    }


}
